<template>
  <view class="edit-baby">
    <customHeader class="edit-baby-title" title="习惯百日行" />
    <perfectInfo
      form-where="ADD_BABY"
      :avatar-info="avatarInfo"
      :student="student"
      :ok="handleOk"
      @change-avatar="handleChangeAvatar"
    />
  </view>
</template>

<script>
import Taro from "@tarojs/taro";
import perfectInfo from "@/components/perfect-info/index";
import customHeader from "@/components/custom-header";
import { addBaby } from "@/libs/api/mine";
import { improveInformation } from "@/libs/api/login";
import { getDefaultAvatar } from "@/libs/api/base-api";
import { clearToken } from "@/libs/util";
import basicDataSet from "@/config/basic-data-set";
export default {
  components: {
    perfectInfo,
    customHeader
  },
  data() {
    return {
      avatarInfo: {},
      student: {}
    };
  },
  onLoad({ student }) {
    student = student ? JSON.parse(student) : {};
    console.log(this.student, "student");
    if (!student.isJump) {
      this.handleInitAvatar();
    }
    if (student?.avatar) {
      this.avatarInfo = {
        id: student?.avatarId,
        avatar: student?.avatar
      };
    }
    this.student = student;
  },
  methods: {
    handleChangeAvatar(data) {
      this.avatarInfo = data;
    },
    /**获取默认头像 */
    async handleInitAvatar() {
      const { data = [] } = await getDefaultAvatar();
      const random = Math.floor(Math.random() * 10);
      const source = data;
      this.avatarInfo = source[random];
    },
    async handleOk(query) {
      if (this.isLoading) return;
      this.isLoading = true;
      Object.assign(query, { avatar: this.avatarInfo.avatar });
      if (this.student.isJump) {
        const loginInfo = Taro.getStorageSync("session_key");
        query = {
          ...query,
          is_have: 1,
          openid: loginInfo?.openid,
          phone: this.student?.phone
        };
      }
      const req = this.student.isJump ? improveInformation : addBaby;
      const [err, { data: { token } = {} }] = await this.$captureCatch(
        req(query)
      );

      if (err) {
        this.$message(message);
        this.isLoading = false;
        return;
      }
      clearToken();
      token && Taro.setStorageSync("token", token);
      basicDataSet.setUser();
      Taro.navigateBack({
        delta: 1,
        complete: () => {
          this.isLoading = false;
        }
      });
    }
  }
};
</script>

<style lang="scss">
.edit-baby-title {
  background-color: #ffffff;
}
</style>
